package com.example.yls.demof;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by yls on 2019/5/17.
 */

public class MyView extends View{
    private Paint paint = new Paint();
    private float center;
    private float radius;

    //双缓冲
    private Bitmap bufBitmap;
    private Canvas bufCanvas;

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);

        StartThread();
    }

    private void StartThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    postInvalidate();
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.e("MyView", "width = " + right + " height = " + bottom);

        if(bufBitmap == null){
            bufBitmap = Bitmap.createBitmap(right, bottom, Bitmap.Config.ARGB_8888);
        }

        if(bufCanvas == null){
            bufCanvas = new Canvas(bufBitmap);
        }
    }

    public void setCenter(float center) {
        this.center = center;
        drawBuf();
    }

    public void setRadius(float radius) {
        this.radius = radius;
        drawBuf();
    }

    private void drawBuf() {
        bufCanvas.drawColor(Color.WHITE);
        bufCanvas.drawCircle(center, center, 50, paint);
        bufCanvas.drawCircle(300, 300, radius, paint);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e("MyView", "onDraw");
        //同时画
        /*canvas.drawRect(100, 100, 300, 300, paint);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        canvas.drawCircle(200, 200, 100, paint);*/
        //画缓冲区
        canvas.drawBitmap(bufBitmap, 0, 0, paint);
    }
}
